#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/7/20 11:07
# @Author  : Samge

import PyQt5.QtCore as qc
from PyQt5.QtWidgets import QFileDialog, QMessageBox

from itkz.resources.utils import file_util, date_util, tip_util

config = qc.QSettings("config.ini", qc.QSettings.IniFormat)


def value(p_str, defaultValue=None):
    return config.value(p_str) or defaultValue


def setValue(p_str, Any):
    config.setValue(p_str, Any)


def get_key_sql_hist(name):
    """
    获取 sql语句查询记录 的配置名
    :param name:
    :return:
    """
    return f"{name}/sql_history"


def get_sql_hist(name):
    """
    获取 sql语句查询记录 列表
    :param name:
    :return:
    """
    return config.value(get_key_sql_hist(name)) or []


def set_sql_hist(name, sql_hist):
    """
    保存 sql语句查询记录 列表
    :param name:
    :param sql_hist:
    :return:
    """
    return config.setValue(get_key_sql_hist(name), sql_hist)


def import_config(self):
    """
    导入配置
    :param self:
    :return:
    """
    config_path, filetype = QFileDialog.getOpenFileName(self, "选取文件", "C:/", "Text Files (*.ini)")
    if not config_path:
        return
    print(f'import_config {config_path} -> {config.fileName()}')
    if not str(config_path).endswith('.ini'):
        tip_util.show_tip(self, "只支持导入.ini后缀的配置文件", tip_type=QMessageBox.critical)
        return
    config_txt = file_util.read_txt_file(config_path)
    file_util.save_txt_file(config_txt, config.fileName())
    tip_util.show_tip(self, "导入配置成功，重启程序后生效")


def export_config(self):
    """
    导出配置
    :param self: 保存配置的文件路径
    :return:
    """
    config_path, ok = QFileDialog.getSaveFileName(self, "配置另存为",
                                                  f"C:/policy_config_{date_util.get_today_str(format='%Y%m%d')}.ini",
                                                  "Text Files (*.ini)")
    if not ok:
        return
    print(f'export_config {config.fileName()} -> {config_path}')
    config_txt = file_util.read_txt_file(config.fileName())
    file_util.save_txt_file(config_txt, config_path)
    tip_util.show_tip(self, f"成功保存配置到：{config_path}")

